//EntityControl.cs
using System;
using System.Collections;

using NHibernate;

namespace mborn.DAL
{
	public class EntityControl
	{
		private static EntityControl entity;
		private string _AssemblyName;
		static readonly object padlock = new object();
 
		public static EntityControl CreateEntityControl(string AssemblyName)
		{
			if(entity == null)
			{
				lock(padlock)
				{
					if(entity == null)
					{
						entity = new EntityControl();
						entity._AssemblyName = AssemblyName;
					}
				}
			}
			return entity;
		}

		public void AddEntity(Object entity)
		{
			ISession session = SessionFactory.OpenSession(_AssemblyName);
			ITransaction transaction = session.BeginTransaction();
			try
			{
				session.Save(entity);
				transaction.Commit();
			}
			catch(Exception ex)
			{
				transaction.Rollback();
				throw ex;
			}
			finally
			{
				session.Close();
			}
		}
             
		public void UpdateEntity(Object entity,Object key)
		{
			ISession session = SessionFactory.OpenSession(_AssemblyName);
			ITransaction transaction = session.BeginTransaction();
			try
			{
				session.Update(entity,key);
				transaction.Commit();
			}
			catch(Exception ex)
			{
				transaction.Rollback();
				throw ex;
			}
			finally
			{
				session.Close();
			}
		}
         
		public void DeleteEntity(object entity)
		{
			ISession session = SessionFactory.OpenSession(_AssemblyName);
			ITransaction transaction = session.BeginTransaction();
             
			try
			{
				session.Delete(entity);
				transaction.Commit();
			}
			catch(Exception ex)
			{
				transaction.Rollback();
				throw ex;
			}
			finally
			{
				session.Close();
			}
		}

		public IList GetEntities(string strHQL)
		{
			IList lst;
			ISession session = SessionFactory.OpenSession(_AssemblyName);
			ITransaction transaction = session.BeginTransaction();
 
			lst=session.Find(strHQL);
			transaction.Commit();
			session.Close();
			return lst;
		}
	}
}
